package com.example.demo.config.costum;

import com.example.demo.common.consts.StringConst;
import com.example.demo.common.exception.BusinessException;
import com.example.demo.common.exception.enums.MessageEnum;
import com.example.demo.common.utils.RedisUtil;
import com.example.demo.domian.UserVo;
import com.example.demo.common.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Name UserVoArgumentResolver
 * @Description 自定义参数转换器(对@RequestBody 绑定的参数无效，对非json数据生效)
 * @Author wen
 * @Date 2019-08-02
 */
@Component
public class UserVoArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?>[] parameterTypes = parameter.getMethod().getParameterTypes();
        return UserVo.class.isAssignableFrom(parameterTypes[0]);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        UserVo userVo = null;
        String token = request.getHeader(StringConst.USER_ACCESS_TOKEN_KEY);
        if(StringUtils.isNotBlank(token)) {
            String userVoJson = RedisUtil.get(token);
            if (StringUtils.isNotBlank(userVoJson)) {
                userVo = JsonUtil.parse(userVoJson, UserVo.class);
            }
        }
        if(userVo == null){
            throw BusinessException.build(MessageEnum.USER_SESSION_NOT_EXITS);
        }
        return userVo;
    }
}
